package com.heima.user.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustException;
import com.heima.feigns.article.ArticleFeign;
import com.heima.feigns.wemedia.WemediaFeign;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.constants.AdminConstants;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.AuthDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserRealname;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.mapper.ApUserRealnameMapper;
import com.heima.user.service.ApUserRealnameService;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class ApUserRealnameServiceImpl extends ServiceImpl<ApUserRealnameMapper, ApUserRealname> implements ApUserRealnameService {

    @Autowired
    private ApUserMapper apUserMapper;

    @Autowired
    private WemediaFeign wemediaFeign;

    @Autowired
    private ArticleFeign articleFeign;

    /**
     * app端用户认证列表查询
     *
     * @param dto
     * @return
     */
    @Override
    @GlobalTransactional(rollbackFor = Exception.class)
    public ResponseResult findUserByStatus(AuthDto dto) {
        // 参数校验
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        // 分页参数判断
        dto.checkParam();
        // 分页查询
        LambdaQueryWrapper<ApUserRealname> wrapper = new LambdaQueryWrapper<>();
        // 用户状态判空
        if (dto.getStatus() != null) {
            wrapper.eq(ApUserRealname::getStatus, dto.getStatus());
        }
        IPage<ApUserRealname> iPage = this.page(new Page<>(dto.getPage(), dto.getSize()), wrapper);
        // 返回结果
        return new PageResponseResult(dto.getPage(), dto.getSize(), (int) iPage.getTotal(), iPage.getRecords());
    }

    /**
     * 根据status认证审核
     *
     * @param dto
     * @param status
     * @return
     */
    @Override
    public ResponseResult updateStatusById(AuthDto dto, Short status) {
        // 检查参数dto,dto.id
        if (dto == null || dto.getId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        // 获取user-id
        // 根据dto获取pojo
        ApUserRealname apUserRealname = getById(dto.getId());
        Integer userId = apUserRealname.getUserId();
        if (apUserRealname == null || userId == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        // 对apUser账号判空，是否正常
        ApUser apUser = apUserMapper.selectById(userId);
        if (apUser == null || apUser.getStatus()) {
            return ResponseResult.errorResult(AppHttpCodeEnum.APUSER_STATUS_ERROR);
        }
        // 更新信息，修改状态status，update time，msg  ==>  ap-user-realname
        apUserRealname.setStatus(status);
        apUserRealname.setUpdatedTime(new Date());
        if (StringUtils.isNotBlank(dto.getMsg())) {
            apUserRealname.setReason(dto.getMsg());
        }
        this.updateById(apUserRealname);

        // 根据status是否通过
        // 不通过直接返回
        if (AdminConstants.PASS_AUTH == status.intValue()) {
            // 通过
            // 1，创建自媒体账号
            WmUser wmUser = this.createWmUser(apUser);
            if (wmUser == null || wmUser.getId() == null) {
                CustException.cust(AppHttpCodeEnum.WMUSER_ADD_ERROR);
            }

            // 2. 创建作者账号
            boolean flag = this.createApAuthor(wmUser);
            if (!flag) {
                CustException.cust(AppHttpCodeEnum.APAUTHOR_ADD_ERROR);
            }

            // 更新ap-user的flag为自媒体用户1
            apUser.setFlag((short) 1);
            //int i = 1/0;
            apUserMapper.updateById(apUser);
        }

        // return
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 1，创建自媒体账号
     *
     * @param apUser
     * @return
     */
    private WmUser createWmUser(ApUser apUser) {
        // 判空，设置属性值
        if (wemediaFeign.findByName(apUser.getName()) == null) {
            WmUser wmUser = new WmUser();
            wmUser.setApUserId(apUser.getId());
            wmUser.setName(apUser.getName());
            wmUser.setPassword(apUser.getPassword());
            wmUser.setSalt(apUser.getSalt());
            wmUser.setImage(apUser.getImage());
            wmUser.setPhone(apUser.getPhone());
            wmUser.setScore(100);
            wmUser.setStatus(9);
            wmUser.setType(0);
            wmUser.setCreatedTime(new Date());
            return wemediaFeign.save(wmUser);
        }
        return null;
    }

    /**
     * 2. 创建作者账号
     *
     * @param wmUser
     * @return
     */
    private boolean createApAuthor(WmUser wmUser) {
        ApAuthor author = articleFeign.findByUserId(wmUser.getApUserId());
        if (author == null) {
            author = new ApAuthor();
            author.setCreatedTime(new Date());
            author.setName(wmUser.getName());
            author.setType(AdminConstants.AUTHOR_TYPE);
            author.setUserId(wmUser.getApUserId());
            author.setWmUserId(wmUser.getId());
            ResponseResult result = articleFeign.save(author);
            if (result.getCode() == 0) {
                return true;
            }
        }
        return false;
    }
}
